package name_service;

import java.io.*;
import java.net.Socket;

public class NameServerCom extends Thread {
    private NameServer nameServer;
    private Socket socket;
    private String splitString = Config.splitString;

    public NameServerCom(NameServer nameServer, Socket connectionSocket) {
        this.socket = connectionSocket;
        this.nameServer = nameServer;
    }

    @Override
    public void run() {
        try {
            nameServer.addConnection();
            ObjectInputStream inFromClient = new ObjectInputStream(socket.getInputStream());
            ObjectOutputStream outFromServer = new ObjectOutputStream(socket.getOutputStream());
            Object object = inFromClient.readObject();
            //NameServiceMessage nameServiceMessage = (NameServiceMessage) object;
            String nameServiceMessageString = (String) object;
            String[] nsmSplit =  nameServiceMessageString.split(splitString);
            NameServiceMessage nameServiceMessage = new NameServiceMessage(nsmSplit[0],nsmSplit[1],nsmSplit[2],Integer.parseInt(nsmSplit[3]),nsmSplit[4],Integer.parseInt(nsmSplit[5]));
            if (nameServiceMessage.getType().equals("rebind")) {
                if(NameServer.DEBUGGER) System.out.println("Type rebind von Client " + nameServiceMessage.getName() + " : " + socket.getInetAddress().toString());
                nameServer.rebind(nameServiceMessage.getName(), nameServiceMessage.getReference());
            } else if (nameServiceMessage.getType().equals("resolve")) {
                if(NameServer.DEBUGGER) System.out.println("Type resolve von Client " + nameServiceMessage.getName() + " : " + socket.getInetAddress().toString());
                outFromServer.writeObject(nameServer.resolve(nameServiceMessage.getName()).sendMsg());
            } else {
                if(NameServer.DEBUGGER) System.out.println("Type Unbekannt von Client " + nameServiceMessage.getName() + " : " + socket.getInetAddress().toString());
            }

            outFromServer.close();
            inFromClient.close();
            nameServer.removeConnection();
            socket.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
